package com.example.md.mddemo.java8.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * Copyright © 2018年 mddemo. All rights reserved.
 *
 * @author 临江仙 hzqiuxm@163.com
 * forkjoin来模拟计算自然数累加和,如果你计算的需要返回值就继承RecursiveTask 抽象类，如果不需要返回值就继承
 * RecursiveAction 抽象类。
 * @date 2018/12/1 13:56
 * @Since 1.0.0
 */
public class ConcurrencyCalculator extends RecursiveTask<Long> {

    private final long start;
    private final long end;
    private static long THREADNUM = 5;

    public ConcurrencyCalculator(long start, long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {
        long result = 0;

        if((end - start) < THREADNUM){
            for (long x = start; x < end; x++) {
                result += x;
            }

        }else{
            long mid = (start+end)/2;
            ConcurrencyCalculator leftCalculator = new ConcurrencyCalculator(start, mid);
            ConcurrencyCalculator rightCalculator = new ConcurrencyCalculator(mid, end);

            leftCalculator.fork();
            rightCalculator.fork();

            result += (leftCalculator.join() + rightCalculator.join());
        }

        return result;
    }
}
